package org.wmq.taskschedule.job;

import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wmq.taskschedule.biz.model.DO.Task;
import org.wmq.taskschedule.controller.TaskController;
import org.wmq.taskschedule.service.TaskService;
import org.wmq.taskschedule.service.ThreadPoolService;

import java.time.LocalDateTime;

@Component
@Slf4j
public class TimerExecutor {
    @Autowired
    private TaskService taskService;
    @Autowired
    private ThreadPoolService threadPoolService;
    @Autowired
    private TaskController taskController;



    @XxlJob("timerExecutor")
    public void execute(){
        // 获取当前小时的开始时间 (例如: 2023-10-15 06:00:00)
        LocalDateTime startOfCurrentHour = LocalDateTime.now().withMinute(0).withSecond(0).withNano(0);

        // 获取当前小时的结束时间 (例如: 2023-10-15 06:59:59.999999999)
        LocalDateTime endOfCurrentHour = startOfCurrentHour.plusHours(1).minusNanos(1);

        this.taskService.lambdaQuery().
                select(Task::getId).
                eq(Task::getStatus, Task.BEGINNING).eq(Task::getScheduleFlag, 1).
                between(Task::getScheduledDate, startOfCurrentHour, endOfCurrentHour).
                list().forEach(
                        task -> {
                            this.threadPoolService.submit(() -> {
                                try {
                                    this.taskController.execute(task.getId());
                                } catch (Exception e) {
                                    log.error("任务执行失败：{}", task.getName(), e);
                                    throw new RuntimeException(e);
                                }
                            });
                        }
                );

    }
}
